package com.mentalhealthplatform.teacherV2.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.mentalhealthplatform.appModels.Task;
import com.mentalhealthplatform.teacherV2.service.TaskServiceV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tasks")
public class TaskControllerV2 {
    @Autowired
    private TaskServiceV2 taskServiceV2;

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    private Map<String, String> filenameToUploadIdMap = new HashMap<>();
    private Map<String, List<PartETag>> uploadPartsMap = new HashMap<>();

    // 获取所有任务
    @GetMapping
    public List<Task> getAllTasks() {
        return taskServiceV2.getAllTasks();
    }

    // 根据ID获取特定任务
    @GetMapping("/{id}")
    public ResponseEntity<Task> getTaskById(@PathVariable Long id) {
        Task task = taskServiceV2.getTaskById(id);
        if (task == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(task);
    }

    // 创建任务
    @PostMapping
    public Task createTask(@RequestBody Task task) {
        return taskServiceV2.saveTask(task);
    }

    // 上传文件分片
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFiles(
            @RequestParam("file") MultipartFile file,
            @RequestParam("filename") String filename,
            @RequestParam("chunkIndex") int chunkIndex,
            @RequestParam("totalChunks") int totalChunks) {
        String uploadId = null;
        try {
            if (chunkIndex == 0) {
                // 初始化分片上传
                InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, filename);
                InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
                uploadId = upresult.getUploadId();
                filenameToUploadIdMap.put(filename, uploadId);
                uploadPartsMap.put(uploadId, new ArrayList<>());
            } else {
                // 获取之前的uploadId
                uploadId = filenameToUploadIdMap.get(filename);
                if (uploadId == null) {
                    throw new IllegalStateException("Upload ID not found for filename: " + filename);
                }
            }

            // 上传分片
            UploadPartRequest uploadPartRequest = new UploadPartRequest();
            uploadPartRequest.setBucketName(bucketName);
            uploadPartRequest.setKey(filename);
            uploadPartRequest.setUploadId(uploadId);
            uploadPartRequest.setInputStream(file.getInputStream());
            uploadPartRequest.setPartSize(file.getSize());
            uploadPartRequest.setPartNumber(chunkIndex + 1);

            UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
            PartETag partETag = uploadPartResult.getPartETag();
            uploadPartsMap.get(uploadId).add(partETag);

            // 如果所有分片上传完成，完成分片上传
            if (chunkIndex == totalChunks - 1) {
                CompleteMultipartUploadRequest completeMultipartUploadRequest =
                        new CompleteMultipartUploadRequest(bucketName, filename, uploadId, uploadPartsMap.get(uploadId));
                ossClient.completeMultipartUpload(completeMultipartUploadRequest);
                uploadPartsMap.remove(uploadId);
                filenameToUploadIdMap.remove(filename);

                // 保存文件名到数据库
                Task task = new Task();
                task.setFileName(filename);
                taskServiceV2.saveTask(task);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("filename", filename);
            response.put("chunkIndex", chunkIndex);
            response.put("totalChunks", totalChunks);
            response.put("message", "File chunk uploaded successfully");

            return ResponseEntity.ok(response);
        } catch (OSSException | ClientException | IOException e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("message", "File upload failed");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 删除指定ID的任务
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
        taskServiceV2.deleteTask(id);
        return ResponseEntity.noContent().build();
    }

    // 获取所有已上传文件
    @GetMapping("/uploaded-files")
    public ResponseEntity<List<String>> getAllUploadedFiles() {
        try {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
            List<String> fileNames = new ArrayList<>();
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                fileNames.add(objectSummary.getKey());
            }
            return ResponseEntity.ok(fileNames);
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}